package pers.lance.mvc.rest.plus.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import pers.lance.mvc.rest.plus.dao.BookDao;
import pers.lance.mvc.rest.plus.pojo.Book;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * @ Author     ：LILA3
 * @ Date       ：Created in 6:40 PM 7/26/2018
 */
@Repository
public class BookDaoImpl implements BookDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private String addSql = "insert into book(id, bname, price, pressdate, author) values(?,?,?,?,?)";
    private String updateSql = "update book set bname = ?, price = ?, pressdate = ?, author = ? where id = ?";
    private String deleteSql = "delete book where id = ?";
    private String findById = "select * from book where id = ?";
    private String findAll = "select * from book";

    @Override
    public int insert(Book book) {
        return jdbcTemplate.update(addSql, book.getId(), book.getBname(),
                book.getPrice(), book.getPressDate(), book.getAuthor());
    }

    @Override
    public int update(Book book) {
        return jdbcTemplate.update(updateSql, book.getBname(), book.getPrice(),
                book.getPressDate(), book.getAuthor(), book.getId());
    }

    @Override
    public int delete(Book book) {
        return jdbcTemplate.update(deleteSql, book.getId());
    }

    @Override
    public Book findById(String id) {
        return jdbcTemplate.queryForObject(findById, new BookRowMapper(), id);
    }

    @Override
    public List<Book> findAll() {
        return jdbcTemplate.query(findAll, new BookRowMapper());
    }

    private class BookRowMapper implements RowMapper<Book> {

        @Override
        public Book mapRow(ResultSet resultSet, int i) throws SQLException {
            String id = resultSet.getString("id");
            String bname = resultSet.getString("bname");
            double price = resultSet.getFloat("price");
            Date pressDate = resultSet.getDate("pressDate");
            String author = resultSet.getString("author");
            return new Book(id, bname, price, pressDate, author);
        }
    }
}
